<?php
if (! defined ( 'BASEPATH' ))
    exit ( 'No direct script access allowed' );
class sdk_user {
    var $CI;
    const PASSWORD_SALT = "8461813391"; // 加密的盐
    const USER_NAME_MAX_LENGTH = 20;
    const USER_NAME_MIN_LENGTH = 4;
    const USER_PASSWORD_MIN_LENGTH = 4;
    const MERCHANT_USER_SALT = "niuh39pnva"; // 生成OPENID的盐
    const MESSAGE_CODE_URL = "http://119.29.98.244:8090/code"; // 短信地址
    const MESSAGE_CID = 1;
    public function __construct() {
        $this->CI = & get_instance ();
    }
    
    /**
     *
     * 注册逻辑
     *
     * @name registry
     * @param unknown $data            
     * @param number $need_login            
     * @return string|Ambigous <boolean, string>
     * @author Eifel.Deng 2015年3月19日
     */
    public function register($data, $need_login = 0) {
        $result ['error_code'] = 0;
        $result ['message'] = "注册成功";
        
        /**
         * 校验用户名长度
         */
        $account_no_length = strlen ( $data ['account_no'] );
        if ($account_no_length > self::USER_NAME_MAX_LENGTH || $account_no_length < self::USER_NAME_MIN_LENGTH) {
            $result ['error_code'] = 1;
            $result ['message'] = "用户名的长度只能为4~20位长";
            return $result;
        }
        if (strlen ( $data ['password'] ) < self::USER_PASSWORD_MIN_LENGTH) {
            $result ['error_code'] = 1;
            $result ['message'] = "登录密码长度不能低于" . self::USER_PASSWORD_MIN_LENGTH . "位";
            return $result;
        }
        /**
         * 判断用户名是否存在
         */
        $this->CI->load->model ( "sdk_user_model" );
        if ($this->CI->sdk_user_model->query_user_by_account ( $data ['account_no'] ) != null) {

            $result ['error_code'] = 1;
            $result ['message'] = "用户名已经存在,请重新输入";
            return $result;
        }
        $user_id = $this->insert_new_user ( $data );
        $this->insert_user_log ( $user_id, $data ['mer_id'], "reg" );
        /**
         * 如果注册的时候需要登录,那么进入登录流程,返回值加上token和openid
         */
        if ($need_login) {
            $result += $this->set_user_login ( $user_id, $data ['mer_id'] );
        }
        
        return $result;
    }
    private function insert_new_user($user_data) {
        $user_data ['password'] = $this->get_encrypt_password ( $user_data ['password'] );
        $user_data ['reg_time'] = date ( "Y-m-d H:i:s" );
        $this->CI->load->model ( "sdk_user_model" );
        $user_id = $this->CI->sdk_user_model->insert_new_user ( $user_data );
        return $user_id;
    }
    
    /**
     *
     * 密码加密
     *
     * @param unknown_type $base_password            
     */
    private function get_encrypt_password($base_password) {
        // 加密方式,md5(盐+输入密码);
        return md5 ( self::PASSWORD_SALT . $base_password );
    }
    
    /**
     *
     * 用户登录
     *
     * @name login
     * @param unknown $user_data            
     * @return string|Ambigous <boolean, string>
     * @author Eifel.Deng 2015年3月19日
     */
    public function login($user_data) {
       $result ['error_code'] = 0;
        $result ['message'] = "登录成功";
        
        /**
         * 判断用户名是否存在
         */
        $this->CI->load->model ( "sdk_user_model" );
        
        $user_db_data = $this->CI->sdk_user_model->query_user_by_account ( $user_data ['account_no'] );
        if ($user_db_data == null) {
            $result ['error_code'] = 1;
            $result ['message'] = "用户名或密码错误";
            return $result;
        }
        /**
         * 校验密码
         */
        if ($this->get_encrypt_password ( $user_data ['password'] ) != $user_db_data ['PASSWORD']) {
            $result ['error_code'] = 1;
            $result ['message'] = "用户名或密码错误";
            return $result;
        }
        
        $user_id = $user_db_data ['USER_ID'];
        $this->insert_user_log ( $user_id, $user_data ['mer_id'], "login" );
        
        $result += $this->set_user_login ( $user_id, $user_data ['mer_id'] );
        return $result;
    }
    
    /**
     *
     * 用户登录
     *
     * @name set_user_login
     * @param unknown $user_id            
     * @param unknown $mer_id            
     * @return unknown
     * @author Eifel.Deng 2015年3月19日
     */
    private function set_user_login($user_id, $mer_id) {
        $access_token = md5 ( uniqid () );
        $this->CI->load->model ( "sdk_user_model" );
        $open_id = $this->get_open_id ( $mer_id, $user_id );
        $this->clear_user_token ( $open_id );
        $this->CI->sdk_user_model->update_user_login_info ( $user_id, $mer_id, date ( "Y-m-d H:i:s" ) );
        $this->CI->sdk_user_model->update_user_token ( $open_id, $access_token, $user_id, $mer_id, date ( "Y-m-d H:i:s" ) );
        $result ['OpenId'] = $open_id;
        $result ['AccessToken'] = $access_token;
        return $result;
    }
    
    /**
     *
     * 插入用户日志
     *
     * @name insert_user_log
     * @param unknown $user_id            
     * @param unknown $mer_id            
     * @param string $log_type            
     * @author Eifel.Deng 2015年3月19日
     */
    private function insert_user_log($user_id, $mer_id, $log_type = "login") {
        $this->CI->load->model ( "sdk_user_model" );
        $data = array (
                "USER_ID" => $user_id,
                "LOG_TYPE" => $log_type,
                "MER_ID" => $mer_id,
                "LOG_TIME" => date ( "Y-m-d H:i:s" ) 
        );
        
        $this->CI->sdk_user_model->insert_user_log ( $data );
    }
    /**
     *
     * 校验平台的用户token
     *
     * @name check_user_access_token
     * @param unknown $mer_id            
     * @param unknown $open_id            
     * @param unknown $access_token            
     * @param unknown $enc_string            
     * @author Eifel.Deng 2015年3月19日
     */
    public function check_user_access_token($mer_id, $open_id, $access_token, $enc_string) {
        $result ['ErrorCode'] = 1;
        $result ['ErrorDesc'] = "成功";
        
        $this->CI->load->model ( "mpay_merchant_model" );
        $mer_key = $this->CI->mpay_merchant_model->query_merchant_key ( $mer_id );
        if ($mer_key == null) {
            $result ['ErrorCode'] = 2;
            $result ['ErrorDesc'] = "AppId无效";
            return $result;
        }
        
        /**
         * 校验规则,md5(商户编号,AccessToken,密钥 )
         */
        $local_sign = md5 ( $mer_id . $access_token . $mer_key );
        if ($local_sign != $enc_string) {
            $result ['ErrorCode'] = 5;
            $result ['ErrorDesc'] = "Sign无效";
            return $result;
        }
        $this->CI->load->model ( "sdk_user_model" );
        $user_access_token = $this->CI->sdk_user_model->query_user_access_token ( $open_id );
        if ($user_access_token != $access_token) {
            $result ['ErrorCode'] = 3;
            $result ['ErrorDesc'] = "AccessToken 无效";
            return $result;
        }
        
        $result ['ErrorCode'] = 0;
        $result ['ErrorDesc'] = "AccessToken 验证成功";
        return $result;
    }
    
    /**
     *
     * 修改密码
     *
     * @name change_password
     * @param unknown $data            
     * @author Eifel.Deng 2015年3月19日
     */
    public function change_password($user_data) {
       $result ['error_code'] = 0;
        $result ['message'] = "修改密码成功";
        
        if (strlen ( $user_data ['old_password'] ) < 1) {
            $result ['error_code'] = 1;
            $result ['message'] = "原始密码不能为空";
            return $result;
        }
        if (strlen ( $user_data ['account_no'] ) < 1) {
            $result ['error_code'] = 1;
            $result ['message'] = "用户名不能为空";
            return $result;
        }
        if (strlen ( $user_data ['new_password'] ) < self::USER_PASSWORD_MIN_LENGTH) {
            $result ['error_code'] = 1;
            $result ['message'] = "登录密码长度不能低于" . self::USER_PASSWORD_MIN_LENGTH . "位";
            return $result;
        }
        /**
         * 获取用户信息
         */
        
        $this->CI->load->model ( "sdk_user_model" );
        $user_db_data = $this->CI->sdk_user_model->query_user_by_account ( $user_data ['account_no'] );
        if ($user_db_data == null) {
            $result ['error_code'] = 1;
            $result ['message'] = "用户不存在";
            return $result;
        }
        /**
         * 校验原始密码
         */
        if ($this->get_encrypt_password ( $user_data ['old_password'] ) != $user_db_data ['PASSWORD']) {
            $result ['error_code'] = 1;
            $result ['message'] = "原始密码输入有误";
            return $result;
        }
        $new_password = $this->get_encrypt_password ( $user_data ['new_password'] );
        $this->CI->sdk_user_model->change_password ( $user_data ['account_no'], $new_password );
        $this->insert_user_log ( $user_db_data ['USER_ID'], $user_data ['mer_id'], "change_pwd" );
        return $result;
    }
    /**
     *
     * 登出
     *
     * @name logout
     * @param unknown $data            
     * @return string
     * @author Eifel.Deng 2015年3月19日
     */
    public function logout($user_data) {
       $result ['error_code'] = 0;
        $result ['message'] = "登出成功";
        $this->CI->load->model ( "sdk_user_model" );
        $user_db_data = $this->CI->sdk_user_model->query_user_by_account ( $user_data ['account_no'] );
        if ($user_db_data == null) {
            return $result;
        }
        $open_id = $this->get_open_id ( $user_data ['mer_id'], $user_db_data ['USER_ID'] );
        $this->clear_user_token ( $open_id );
        $this->insert_user_log ( $user_db_data ['USER_ID'], $user_data ['mer_id'], "logout" );
        return $result;
    }
    
    /**
     *
     * 用户登出,删除token
     *
     * @name clear_user_token
     * @param unknown $user_id            
     * @param unknown $mer_id            
     * @return unknown
     * @author Eifel.Deng 2015年3月19日
     */
    private function clear_user_token($open_id) {
        $this->CI->load->model ( "sdk_user_model" );
        $this->CI->sdk_user_model->clear_user_token ( $open_id );
    }
    
    /**
     *
     * 获取用户在商户中的open_id
     *
     * @name get_open_id
     * @param unknown $merchant_id            
     * @param unknown $user_id            
     * @return string
     * @author Eifel.Deng 2015年3月20日
     */
    private function get_open_id($merchant_id, $user_id) {
        return md5 ( $merchant_id . self::MERCHANT_USER_SALT . $user_id );
    }
    
    /**
     *
     * 发送短信验证码
     *
     * @name send_bind_message_code
     * @author Eifel.Deng 2015年3月27日
     */
    public function send_bind_message_code($account_no, $phone_num) {
       $result ['error_code'] = 0;
        $result ['message'] = "";
        $result ['code'] = "";
        $this->CI->load->model ( "sdk_user_model" );
        $account_info = $this->CI->sdk_user_model->query_user_by_account ( $account_no );
        if ($account_info ['BIND_PHONE'] == 1) {
            $result ['error_code'] = 1;
            $result ['message'] = "当前帐号已经绑定过了手机";
            return $result;
        }
        $url = self::MESSAGE_CODE_URL;
        $sign = strtoupper ( dechex ( $phone_num ) );
        
        $url_data = array (
                "number" => $phone_num,
                "cid" => self::MESSAGE_CID,
                "sign" => $this->get_message_sign ( self::MESSAGE_CID, $phone_num ) 
        );
        
        /**
         * 获取短信服务器的code
         */
        $ch = curl_init ();
        $timeout = 2;
        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
        $contents = curl_exec ( $ch );
        curl_close ( $ch );
        
        // 解析数据
        $code_info = json_decode ( $contents, true );
        
        if ($code_info && $code_info ['status'] == 1) {
            $result ['code'] = $code_info ['code'];
        }
        $this->CI->sdk_user_model->update_user_bind_message_code ( $account_no, $phone_num, $result ['code'] );
        return $result;
    }
    
    /**
     *
     * 验证找回
     *
     * @name check_code
     * @param unknown $account_no            
     * @param unknown $code            
     * @author Eifel.Deng 2015年3月27日
     */
    public function check_bind_message_code($account_no, $code) {
       $result ['error_code'] = 0;
        $result ['message'] = "";
        $this->CI->load->model ( "sdk_user_model" );
        $account_info = $this->CI->sdk_user_model->query_user_by_account ( $account_no );
        if ($account_info ['BIND_PHONE'] == 1) {
            $result ['error_code'] = 1;
            $result ['message'] = "当前帐号已经绑定过了手机";
            return $result;
        }
        
        if ($account_info ['BIND_PHONE_MESSAGE_CODE'] != $code) {
            $result ['error_code'] = 1;
            $result ['message'] = "手机验证码不正确";
            return $result;
        }
        $this->CI->sdk_user_model->user_bind_phone_num ( $account_no );
        
        $result ['message'] = "你已经成功绑定了手机!";
        return $result;
    }
    private function get_message_sign($cid, $phone_no) {
        return md5 ( $cid . strtoupper ( dechex ( ( int ) $phone_no ) ) );
    }
}